package com.xup.luckymoney;

//import com.freeme.luckymoney.util.AccessibilityUtils;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

/**
 * setting interface of grab packet
 */
public class MainActivity extends BaseActivity {

    private static final String TAG = "LuckyMoneySettings";
    private static final String SELECTED_NOTIFY_MUSIC_ITEM = "selected_notify_of_redpacket";
    private Dialog mTipsDialog;

    private Switch mOpenAllSwitch;
    private Switch mWeChatLuckyWarningSwitch;
    private Switch mQQLuckyWarningSwitch;
    private Switch mDesktopFloatWindowSwitch;
    private Switch mLuckySoundWarningSwitch;
    private TextView mPlayWaringSoundButton;
    private TextView mTVNotifyName;
    private RelativeLayout selectNotifyMusicView;
    private Dialog selectNotifyMusicDialog;
    private MediaPlayer preMusic, curMusic;
    private ListView selectListView;
    private MyAdapter mAdapter;

    private int selectedNotifyMusicIndex = 0;
    private int preClickedMusic = 0;
    private String[] notifyMusicNames;

    private MyCheckedChangeListener mCheckedChangeListener;

    private static enum LuckyWarningButton {
        ALL,
        WECHAT,
        QQ,
        FLOAT,
        SOUND;
    }

    private Config mConfig = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setTitle(R.string.app_name);

        setContentView(R.layout.activity_lucky_setting);
        /*
        setContentView(R.layout.activity_main);
        getFragmentManager().beginTransaction().add(R.id.container, new MainFragment())
                .commitAllowingStateLoss();
        */

        //fix bug: a line between actionbar and activity
        ActionBar actionBar = getActionBar();
        actionBar.setElevation(0);

        LuckyMoneyApplication.activityStartMain(this);

        mConfig = Config.getInstance(this);
        mCheckedChangeListener = new MyCheckedChangeListener();
        mConfig.musicIndex = selectedNotifyMusicIndex = preClickedMusic =
                Settings.Global.getInt(getContentResolver(), SELECTED_NOTIFY_MUSIC_ITEM, 0);
        initViews();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Config.ACTION_RED_PACKET_SERVICE_CONNECT);
        filter.addAction(Config.ACTION_RED_PACKET_SERVICE_DISCONNECT);
        registerReceiver(qhbConnectReceiver, filter);
    }

    private BroadcastReceiver qhbConnectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isFinishing()) {
                return;
            }
            String action = intent.getAction();
            Log.d(TAG, "receive-->" + action);

            refreshViewState();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        boolean isRunning = LuckyMoneyService.isRunning();
        Log.d(TAG, "onResume isRunning = " + isRunning);

        if (isRunning) {
            if (null != mTipsDialog) {
                mTipsDialog.dismiss();
            }
        }
        refreshViewState();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(qhbConnectReceiver);
        } catch (Exception e) {
        }
        mTipsDialog = null;
    }

    private void initViews() {
        notifyMusicNames = MainActivity.this.getResources()
                .getStringArray(R.array.alarm_music_name);
        mOpenAllSwitch = (Switch) findViewById(R.id.button_all_control);
        mOpenAllSwitch.setChecked((Settings.System.getInt(getContentResolver(),
                Config.LUCKY_MONEY_ENABLED, 0) == 1));
        mWeChatLuckyWarningSwitch = (Switch) findViewById(R.id.button_wechat_lucky_warning);
        mQQLuckyWarningSwitch = (Switch) findViewById(R.id.button_qq_lucky_warning);
        mDesktopFloatWindowSwitch = (Switch) findViewById(R.id.button_desktop_float_window);
        mLuckySoundWarningSwitch = (Switch) findViewById(R.id.button_lucky_sound_warning);

        mPlayWaringSoundButton = (TextView) findViewById(R.id.sound_try_listen);
        mTVNotifyName = (TextView) findViewById(R.id.notify_name);
        mTVNotifyName.setText(notifyMusicNames[selectedNotifyMusicIndex]);

        selectNotifyMusicView = (RelativeLayout) findViewById(R.id.select_red_packet_notify);

        mOpenAllSwitch.setOnCheckedChangeListener(mCheckedChangeListener);
        mWeChatLuckyWarningSwitch.setOnCheckedChangeListener(mCheckedChangeListener);
        mQQLuckyWarningSwitch.setOnCheckedChangeListener(mCheckedChangeListener);
        mDesktopFloatWindowSwitch.setOnCheckedChangeListener(mCheckedChangeListener);
        mLuckySoundWarningSwitch.setOnCheckedChangeListener(mCheckedChangeListener);

        mPlayWaringSoundButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) { // preview warning sound
                mConfig.playNotice();
            }
        });
        selectNotifyMusicView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectNotifyMusicDialog();
            }
        });
    }

    private void refreshViewState() {
        boolean isRunning = LuckyMoneyService.isRunning();

        boolean isEnableSound = mConfig.getNoticeEnable();
        boolean isEnableFloatWindow = mConfig.getFloatWindowEnable();
        boolean isEnableWeChat = mConfig.getWehcatEnable();
        boolean isEnableQQ = mConfig.getQQEnable();

        Log.d(TAG, "refreshView State {running = " + isRunning
                + ",wechat = " + isEnableWeChat
                + ",qq = " + isEnableQQ
                + ",sound = " + isEnableSound
                + ",floatWondiow = " + isEnableFloatWindow
                + "}");

        // set enabled state
        mWeChatLuckyWarningSwitch.setEnabled(isRunning);
        mQQLuckyWarningSwitch.setEnabled(isRunning);
        mDesktopFloatWindowSwitch.setEnabled(isRunning);
        mLuckySoundWarningSwitch.setEnabled(isRunning);

        // set checked state
        mOpenAllSwitch.setChecked(isRunning);
        mWeChatLuckyWarningSwitch.setChecked(isEnableWeChat);
        mQQLuckyWarningSwitch.setChecked(isEnableQQ);
        mDesktopFloatWindowSwitch.setChecked(isEnableFloatWindow);
        mLuckySoundWarningSwitch.setChecked(isEnableSound);
        updateSoundTryState(isEnableSound);
    }

    public class MyCheckedChangeListener implements OnCheckedChangeListener {

        public MyCheckedChangeListener() {
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.button_all_control: // open all function
                    changeLuckyWarningState(LuckyWarningButton.ALL, isChecked);
                    break;
                case R.id.button_wechat_lucky_warning:
                    changeLuckyWarningState(LuckyWarningButton.WECHAT, isChecked);
                    break;
                case R.id.button_qq_lucky_warning:
                    changeLuckyWarningState(LuckyWarningButton.QQ, isChecked);
                    break;
                case R.id.button_desktop_float_window:
                    changeLuckyWarningState(LuckyWarningButton.FLOAT, isChecked);
                    break;
                case R.id.button_lucky_sound_warning:
                    changeLuckyWarningState(LuckyWarningButton.SOUND, isChecked);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * show the audition button when enable sound notify
     */
    private void updateSoundTryState(boolean show) {
        int visible = View.GONE;
        if (show) {
            visible = View.VISIBLE;
        }
        /*if (null != mPlayWaringSoundButton) {
            mPlayWaringSoundButton.setVisibility(visible);
            mPlayWaringSoundButton.setClickable(LuckyMoneyService.isRunning());
        }*/
        if (selectNotifyMusicView != null) {
            selectNotifyMusicView.setVisibility(visible);
            selectNotifyMusicView.setClickable(LuckyMoneyService.isRunning());
        }
    }

    private void changeLuckyWarningState(LuckyWarningButton button, boolean checked) {
        switch (button) {
            case ALL:
                Log.d(TAG, "allButton checked = " + checked);
                boolean isRunning = LuckyMoneyService.isRunning();
                if (checked != isRunning) {
                    //AccessibilityUtils.handleLuckyMoneyServiceEnabled(MainActivity.this, checked);
                    Settings.System.putInt(getContentResolver(), Config.LUCKY_MONEY_ENABLED,
                            checked ? 1 : 0);
                }
                return;
            case WECHAT:
                mConfig.setWechatEnable(checked);
                break;
            case QQ:
                mConfig.setQQEnable(checked);
                break;
            case FLOAT:
                mConfig.setFloatWindowEnable(checked);
                break;
            case SOUND:
                mConfig.setNoticeEnable(checked);
                updateSoundTryState(checked);
                break;
            default:
                break;
        }
    }

    /**
     * show open accessibility service dialog
     */
    public void showOpenAccessibilityServiceDialog() {
        if (mTipsDialog != null && mTipsDialog.isShowing()) {
            return;
        }
        View view = getLayoutInflater().inflate(R.layout.dialog_tips_layout, null);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAccessibilityServiceSettings();
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.open_service_title);
        builder.setView(view);
        builder.setPositiveButton(R.string.open_service_button,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        openAccessibilityServiceSettings();
                    }
                });
        mTipsDialog = builder.show();
    }

    /**
     * open Accessibility Service Settings
     */
    private void openAccessibilityServiceSettings() {
        try {
            Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
            startActivity(intent);
            Toast.makeText(this, R.string.tips, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSelectNotifyMusicDialog() {
        Log.d(TAG, "selectedNotifyMusicIndex = " + selectedNotifyMusicIndex
                + ", preClickedMusic = " + preClickedMusic);
        preClickedMusic = selectedNotifyMusicIndex;
        if (selectNotifyMusicDialog == null) {
            selectNotifyMusicDialog = new Dialog(MainActivity.this);
            selectNotifyMusicDialog.setTitle(R.string.select_red_packet_notify);
            selectNotifyMusicDialog.setContentView(R.layout.notify_music_listview);
        }

        selectListView = (ListView) selectNotifyMusicDialog
                .findViewById(R.id.lv_notify_music);
        mAdapter = new MyAdapter(this);
        selectListView.setAdapter(mAdapter);
        Button okBt = (Button) selectNotifyMusicDialog.findViewById(R.id.ok);
        okBt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curMusic != null) {
                    Log.d(TAG, "curMusic.isPlaying(): " + curMusic.isPlaying());
                }
                if (curMusic != null && curMusic.isPlaying()) {
                    curMusic.stop();
                }
                if (preClickedMusic != selectedNotifyMusicIndex) {
                    mConfig.needUpdate = true;
                    mConfig.musicIndex = selectedNotifyMusicIndex = preClickedMusic;
                    Settings.Global.putInt(getContentResolver(), SELECTED_NOTIFY_MUSIC_ITEM,
                            selectedNotifyMusicIndex);
                    if (selectNotifyMusicDialog != null && selectNotifyMusicDialog.isShowing()) {
                        selectNotifyMusicDialog.dismiss();
                    }
                    mTVNotifyName.setText(notifyMusicNames[selectedNotifyMusicIndex]);
                }
            }
        });
        Button cancelBt = (Button) selectNotifyMusicDialog.findViewById(R.id.cancel);
        cancelBt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curMusic != null && curMusic.isPlaying()) {
                    curMusic.stop();
                }
                if (selectNotifyMusicDialog != null && selectNotifyMusicDialog.isShowing()) {
                    selectNotifyMusicDialog.dismiss();
                }
            }
        });

        selectNotifyMusicDialog.show();
    }

    private class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MyAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return notifyMusicNames.length;
        }

        @Override
        public Object getItem(int position) {
            return notifyMusicNames[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder mViewHolder;
            if (convertView == null) {
                mViewHolder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.notify_music_listview_item, null);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }

            mViewHolder.tvItem = (TextView) convertView.findViewById(R.id.tv_notify_music_item);
            mViewHolder.tvItem.setText(notifyMusicNames[position]);

            mViewHolder.radioButton = (RadioButton) convertView.findViewById(R.id.bt_radio_item);
            mViewHolder.radioButton.setClickable(false);
            if (position == preClickedMusic) {
                mViewHolder.radioButton.setChecked(true);
            } else {
                mViewHolder.radioButton.setChecked(false);
            }

            mViewHolder.listItem = (LinearLayout) convertView.findViewById(R.id.list_item);
            mViewHolder.listItem.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "preClickedMusic = " + preClickedMusic + ", position = " + position);
                    Log.d(TAG, "curMusic = " + curMusic);
                    if (preClickedMusic != position || curMusic == null) {
                        curMusic = MediaPlayer.create(
                                MainActivity.this, mConfig.nitofyMusicID[position]);
                        preClickedMusic = position;
                        selectListView.getItemAtPosition(position);
                        notifyDataSetChanged();
                        if (preMusic != null && preMusic.isPlaying()) {
                            preMusic.stop();
                        }
                    }
                    Log.d(TAG, "curMusic = " + curMusic +
                            ", curMusic.isPlaying(): " + curMusic.isPlaying());
                    if (!curMusic.isPlaying()) {
                        curMusic.start();
                        preMusic = curMusic;
                    }
                }
            });

            return convertView;
        }

        private class ViewHolder {
            public LinearLayout listItem;
            public RadioButton radioButton;
            public TextView tvItem;
        }
    }
}
